﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;

namespace TracNghiemChonTruong.Class
{
    class SqlHelper : IDisposable
    {
        SqlConnection _connection;
        public SqlConnection Connection
        {
            get { return _connection; }
        }
        SqlCommand _command;

        public IList<string> ParamKeys
        {
            get;
            set;
        }

        public IList<object> ParamValues
        {
            get;
            set;
        }

        public SqlHelper()
        {
            _connection = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["htsConnectionString"].ToString());
            _connection.Open();
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public int ExecuteNonQuery(string cmdText, CommandType cmdType = CommandType.Text)
        {
            int val = 0;
            using (var command = new SqlCommand(cmdText, _connection))
            {
                PrepareCommand(command, _connection, null, cmdType);
                val = command.ExecuteNonQuery();
                command.Parameters.Clear();
            }
            return val;
        }

        public void MappingTable(string cmdText, DataTable table)
        {
            using (var adapter = new SqlDataAdapter(cmdText, _connection))
            {
                var command = new SqlCommandBuilder(adapter);
                adapter.TableMappings.Add(table.TableName, table.TableName);
                adapter.Update(table);
            }
        }

        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public object ExecuteScalar(string cmdText, CommandType cmdType = CommandType.Text)
        {
            object val;
            using (var command = new SqlCommand(cmdText, _connection))
            {
                PrepareCommand(command, _connection, null, cmdType);
                val = command.ExecuteScalar();
                command.Parameters.Clear();
            }
            return val;
        }

        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public SqlDataReader ExecuteReader(string cmdText, CommandType cmdType = CommandType.Text)
        {
            _command = new SqlCommand(cmdText, _connection);
            PrepareCommand(_command, _connection, null, cmdType);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                SqlDataReader reader = _command.ExecuteReader(CommandBehavior.CloseConnection);
                _command.Parameters.Clear();

                return reader;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataTable dt = ExecuteDataTable(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A DataTable containing the results</returns>
        public DataTable ExecuteDataTable(string cmdText, CommandType cmdType = CommandType.Text)
        {
            DataTable dt = new DataTable();
            using (var command = new SqlCommand(cmdText, _connection))
            {
                PrepareCommand(command, _connection, null, cmdType);
                using (SqlDataAdapter da = new SqlDataAdapter(command))
                {
                    da.Fill(dt);
                }
                command.Parameters.Clear();
            }
            return dt;
        }

        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataTable dt = ExecuteDataTable(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A DataTable containing the results</returns>
        public DataSet ExecuteDataSet(string cmdText, CommandType cmdType = CommandType.Text)
        {
            DataSet ds = new DataSet();
            using (var command = new SqlCommand(cmdText, _connection))
            {
                PrepareCommand(command, _connection, null, cmdType);
                using (SqlDataAdapter da = new SqlDataAdapter(command))
                {
                    da.Fill(ds);
                }
                command.Parameters.Clear();
            }
            return ds;
        }

        /// <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();

            //cmd.Connection = conn;
            cmd.CommandTimeout = 200;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (ParamKeys != null && ParamKeys.Count > 0)
            {
                if (ParamKeys.Count != ParamValues.Count) throw new IndexOutOfRangeException();

                for (int i = 0; i < ParamKeys.Count; i++)
                {
                    cmd.Parameters.AddWithValue(ParamKeys[i], ParamValues[i] ?? DBNull.Value);
                }
            }
        }

        public void Dispose()
        {
            // release Command
            if (_command != null)
            {
                _command.Dispose();
                _command = null;
            }
            _connection.Close();
            _connection.Dispose();
        }
    }
}
